import java.util.Arrays;

public class TextHeap {
    public int[] elem;
    public int useSize;
    public TextHeap() {
        this.elem = new int[10];
    }
    public void initElem(int[] array) {
        for (int i = 0; i < array.length; i++) {
            elem[i] = array[i];
            useSize++;
        }
    }
    public void createBigHeap() {
        for(int parent = (useSize-1-1)/2; parent >= 0; parent--) {
            siftDown(parent,useSize);
        }
    }
    public void swap(int child, int parent) {
        int cur = elem[child];
        elem[child] = elem[parent];
        elem[parent] = cur;
    }
    //大根堆
    public void siftDown(int parent, int end) {
        int child = 2*parent+1;
        while(child < end) {
            if(child + 1 < end && elem[child] < elem[child+1]) {
                child++;
            }
            if(elem[child] > elem[parent]) {
                swap(child,parent);
                parent = child;
                child = 2*parent+1;
            }else {
                break;
            }
        }
    }
    public int poll() {
        int cur = elem[0];
        elem[0] = elem[useSize-1];
        elem[useSize-1] = cur;
        useSize--;
        siftDown(0,useSize);
        return cur;
    }
    public void offer(int val) {
        if(isFull()) {
            this.elem = Arrays.copyOf(elem,2*elem.length);
            //扩容
        }
        elem[useSize] = val;
        useSize++;
        siftUp(useSize-1);
    }
    //小根堆
    public void siftUp(int child) {
        int parent = (child-1)/2;
        while(parent >= 0) {
            if(elem[parent] < elem[child]) {
                swap(child,parent);
                child = parent;
                parent = (child-1)/2;
            }else {
                break;
            }
        }
    }
    public boolean isFull() {
        return useSize == elem.length;
    }
    public void heapSort() {
        int end = useSize-1;
        while (end > 0) {
            swap(0,end);
            siftDown(0,end-1);
            end--;
        }
    }
}
